package com.example.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.article.mapper.ApArticleConfigMapper;
import com.example.article.mapper.ApArticleContentMapper;
import com.example.article.mapper.ApArticleMapper;
import com.example.article.service.ApArticleService;
import com.example.common.constants.ArticleConstants;
import com.example.common.redis.RedisCache;
import com.example.model.article.dtos.ArticleDto;
import com.example.model.article.dtos.ArticleHomeDto;
import com.example.model.article.pojos.ApArticle;
import com.example.model.article.pojos.ApArticleConfig;
import com.example.model.article.pojos.ApArticleContent;
import com.example.model.article.vos.HotArticleVo;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.common.enums.AppHttpCodeEnum;
import com.example.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    private final static short MAX_PAGE_SIZE = 50;


    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        Integer size = dto.getSize();
        //分页校验
        if(size == null || size == 0){
            size = 10;
        }

        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);

        //默认的type
        if(!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //频道参数校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if(dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        System.out.println("type "+type);
        System.out.println("MaxTime "+dto.getMaxBehotTime());
        System.out.println("MinTime "+dto.getMinBehotTime());

        dto.setOffset((dto.getPage()-1)*dto.getSize());
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        System.out.println("apArticle1 "+apArticle.toString());

        if(dto.getId() == null){
            save(apArticle);
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else{
            updateById(apArticle);
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }
        System.out.println("apArticle2 "+apArticle.toString());

        String res = String.valueOf(apArticle.getId());
        System.out.println("res "+res);

        createArticleIndex(apArticle,dto);

        ApArticle apArticle1 = apArticleMapper.selectById(res);



        return ResponseResult.okResult(res);
    }

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        System.out.println("firstPage "+firstPage);

        if("8".equals(dto.getTag())){
            dto.setTag("__all__");
        }
        System.out.println(dto);
        if(firstPage){
            String jsonStr = redisCache.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(!StringUtils.isEmpty(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(dto, type);
    }

    @Override
    public ResponseResult loadRecommendData(String userId) {
        String line;
        try {
            String[] my_args = new String[]{"python", "E:/pythonProject/test1.py", String.valueOf(userId)};
            Process proc = Runtime.getRuntime().exec(my_args);//执行脚本

            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
//            while ((line = reader.readLine()) != null) {
//                line = reader.readLine();
//                System.out.println(line);
//
//            }
            line = reader.readLine();
            reader.close();
            proc.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        System.out.println(line);
        JSONArray jsonArray = JSON.parseArray(line);
        String[] array = jsonArray.toArray(new String[0]);

        List<ApArticle> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            ApArticle apArticle = apArticleMapper.selectById(array[i]);
            list.add(apArticle);
        }
        return ResponseResult.okResult(list);
    }

    @Autowired
    private KafkaTemplate kafkaTemplate;

    private void createArticleIndex(ApArticle apArticle,ArticleDto dto) {

        try {
            SearchArticleVo searchArticleVo = new SearchArticleVo();
            BeanUtils.copyProperties(apArticle,searchArticleVo);
            searchArticleVo.setContent(dto.getContent());
            searchArticleVo.setId(Long.valueOf(apArticle.getId()));
            log.info("执行到这里了 {}",searchArticleVo.toString());

            kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
